# encoding:utf8
"""
@File        : json_extract.py
@Time        : 2019/7/10 17:05
@Author      : zhaoy
@Email       : zhaoyao@shandiangou.cc
@Description : 
"""


def extract(item, path):
    """

    :param data:
    :param path:
    :return:
    """
    if not isinstance(item, dict):
        raise TypeError('item 必须为字典类型')
    dt = item
    json_path = path.split('.')
    try:
        for path in json_path:
            dt = dt.get(path)
    except AttributeError:
        raise AttributeError('数据解析出错!')
    return dt


def add(item, path, dct):
    json_path = path.split('.')
    lst_data = extract(item, path)
    for i in lst_data:
        if not isinstance(i, dict):
            raise TypeError('列表元素 必须为字典类型')
        i.update(dct)
    for path in json_path:
        if isinstance(item[path], list):
            item[path] = lst_data
        else:
            dict.__getitem__(item, path)
            dict.__setitem__(item, path, None)
    return item
